package com.tiankong.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiankong.product.entity.Attr;
import com.tiankong.product.entity.AttrAttrgroup;
import com.tiankong.product.enums.Type;
import com.tiankong.product.mapper.AttrMapper;
import com.tiankong.product.service.AttrAttrgroupService;
import com.tiankong.product.service.AttrGroupService;
import com.tiankong.product.service.AttrService;
import com.tiankong.product.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品属性 服务实现类
 * </p>
 *
 * @author scl
 * @since 2021-03-22
 */
@Service
public class AttrServiceImpl extends ServiceImpl<AttrMapper, Attr> implements AttrService {

    @Autowired
    private AttrAttrgroupService relationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public void saveAttr(Attr attr) {
        //1、保存基本数据
        this.save(attr);
        //2、保存关联关系
        if(attr.getAttrType() == Type.Attr.BASE){
            saveRelation(attr);
        }
    }

    private void saveRelation(Attr attr) {
        if (attr.getAttrGroupId() != null) {
            AttrAttrgroup relationEntity = new AttrAttrgroup();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            relationService.saveRelation(relationEntity);
        }
    }

    @Override
    public void batchDelete(List<Long> ids) {
        removeByIds(ids);
        relationService.update().in("attr_id",ids).remove();
    }

    @Override
    public Attr getAttrInfo(Long attrId) {
        Attr attr = getById(attrId);
        if(attr.getAttrType() == Type.Attr.BASE){
            //1、设置分组信息
            AttrAttrgroup attrgroupRelation = relationService.query().eq("attr_id", attrId).one();
            if(attrgroupRelation!=null){
                attr.setAttrGroupId(attrgroupRelation.getAttrGroupId());
            }
        }
        //2、设置分类信息
        Long catelogId = attr.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attr.setCatelogPath(catelogPath);

        return attr;
    }

    @Override
    public void updateAttr(Attr attr) {
        this.updateById(attr);
        if(attr.getAttrType() == Type.Attr.BASE){
            relationService.update().eq("attr_id",attr.getAttrId()).remove();
            saveRelation(attr);
        }
    }
}
